<?php
/*
*
* ЯДРО СИСТЕМЫ
*
*/

/*
if ( !empty($_SERVER['OLDPWD']) )
{
    $_wd = $_SERVER['OLDPWD'].'/../';

    chdir($_wd);
    error_log(sprintf("Set CWD to: %s...\n\n",$_wd));
}
*/

// Подключаем классы БД
require_once('class/customer.class.php');
require_once('class/document.class.php');
require_once('class/dictionary.class.php');
require_once('class/treatment_subscriber.class.php');
require_once('class/arrival_time.class.php');
require_once('class/invoice.class.php');

// Подключаем модули для создания страниц
require_once('libs/Smarty.class.php');

class LocalCRM
{
    var $_settings;

    function __construct()
    {
	if ( file_exists('core/settings.ini') && ($ini = parse_ini_file('settings.ini',true)) )
	{
	    foreach ( $ini as $section => $keys )
	    {
		foreach ( $keys as $key => $value )
		{
		    if ( !defined(sprintf('%s_%s',$section,$key)) ) { define(sprintf('%s_%s',$section,$key),$value); }
		}
	    }
	    return $this;
	}
	else { die(sprintf('Невозможно обработать конфигурационный файл!<br/>Убедитесь в том что файл %s существует и заполнен корректно.',$_SERVER['DOCUMENT_ROOT'].'/core/settings.ini')); }
    }

    function initSmarty()
    {
	$www = new WWW;

	return $www->_smarty;
    }
}

class WWW extends LocalCRM
{
    var $_smarty;
    var $_template;

    function __construct()
    {
	parent::__construct();

	$this->_smarty = new Smarty();

	$this->_smarty->template_dir       = Path_tmpls;
	$this->_smarty->compile_dir        = '.'.Path_tmpls;

/*
	$this->_smarty->cache_dir          = 'smarty/cache';
	$this->_smarty->config_dir         = 'smarty/configs';
*/

	$this->_smarty->register_modifier("sslash","stripslashes");
	$this->_smarty->assign('upload_max_filesize',ini_get('upload_max_filesize'));

# Загрузка справочников
	$this->loadDictionary('manager'); // Менеджеры
    }

    function loadDictionary($dict)
    {
	$db = new DB;
	if ( $dict == 'default' )
	{
	    $array = array
	    (
		array
		(
		    'title'	=> 'Номер лиц.счёта',
		    'name'	=> 'account_id',
		),
		array
		(
		    'title'	=> 'Название',
		    'name'	=> 'customer_name',
		),
		array
		(
		    'title'	=> 'Номер договора',
		    'name'	=> 'contract_number',
		),
		array
		(
		    'title'	=> 'Контактная информация',
		    'name'	=> 'contact',
		),
		array
		(
		    'title'	=> 'E-Mail',
		    'name'	=> 'email',
		),
		array
		(
		    'title'	=> 'Группа',
		    'name'	=> 'group_name',
		),
		array
		(
		    'title'	=> 'Статус',
		    'name'	=> 'status_name',
		),
		array
		(
		    'title'	=> 'Ответственный менеджер',
		    'name'	=> 'manager_name',
		),
	    );

	    $this->_smarty->assign($dict.'s',$array);
	}
	elseif ( $dict == 'custom' )
	{
	    $db->_query = 'SELECT * FROM `field_name` ORDER BY `field_name`';

	    foreach ( $db->_getDataArray() as $field )
	    {
		$array[] = array
		(
		    'id'	=> $field['id'],
		    'name'	=> 'custom_field_'.$field['id'],
		    'title'	=> $field['field_name']
		);
	    }

	    $this->_smarty->assign($dict.'s',$array);
	}
	else
	{
	    $db->_query = sprintf('SELECT * FROM `%1$s` ORDER BY `%1$s_name`',$dict);
	    $this->_smarty->assign($dict.'s',$db->_getDataArray());
	}
    }

    function template($path)
    {
	$this->_template = $path;
    }

    function show()
    {
	$this->_smarty->assign('MENU',$this->_smarty->fetch('admin/_menu.html'));
	$this->_smarty->display($this->_template);
    }

    function fetch()
    {
	$this->_smarty->assign('MENU',$this->_smarty->fetch('admin/_menu.html'));
	return $this->_smarty->fetch($this->_template);
    }
}

class DB extends LocalCRM
{
    var $_db;
    var $_table;
    var $_query;
    var $_result;

    function __construct()
    {
	parent::__construct();

	if ( $this->_db = mysql_connect(DB_Host,DB_User,DB_Pass) )
	{
	    mysql_query('SET NAMES utf8',$this->_db);
	    mysql_select_db(DB_Name,$this->_db)||die('Database select failed');
	}

	$this->_limit_offset	= 0;
	$this->_limit_count	= 20;
    }

    function setOrder($field,$dir)
    {
	$this->_order_field = $field;

	if ( $dir == 'desc' )
	{
	    $this->_order_dir = 'DESC';
	}
	else
	{
	    $this->_order_dir = 'ASC';
	}

	return $this;
    }

    function setPage($page)
    {
	if ( $page>0 ) { $page--; }

	if ( is_numeric($page) )
	{
	    $this->_limit_offset = $page*$this->_limit_count;
	}

	return $this;
    }

    function setLimit($limit)
    {
	if ( is_numeric($limit) )
	{
	    $this->_limit_count = $limit;
	}

	return $this;
    }

    function insert($data)
    {
	if ( !empty($this->_table) && is_array($data) )
	{
	    $this->_query = sprintf('INSERT INTO `%s` (%s) VALUES (%s)',$this->_table,implode(',',array_keys($data)),implode(',',array_values($data)));
	    mysql_query($this->_query);
	    if ( mysql_affected_rows()==1 ) { return $this; }
	}
    }

    function update($id,$data)
    {
	if ( !empty($this->_table) && is_array($data) && is_numeric($id) )
	{
	    foreach ( $data as $key => $value )
	    {
		$field[] = sprintf('`%s`=\'%s\'',$key,mysql_escape_string($value));
	    }

	    mysql_query(sprintf('UPDATE `%s` SET %s WHERE `id`=%d',$this->_table,implode(',',$field),$id));
	    if ( mysql_affected_rows()==1 ) { return $this; }
	    else { die(mysql_error()); }
	}
    }

    function like($data)
    {
	if ( is_array($data) )
	{
	    $this->_query = sprintf('SELECT `id`,`%2$s` FROM `%1$s` WHERE `%2$s` LIKE \'%3$s%%\' LIMIT 50',$this->_table,$data[0],$data[1]);

	    if ( $this->_result = mysql_query($this->_query) )
	    {
		while ( $row = mysql_fetch_row($this->_result) )
		{
		    $data[] = array('value'=>$row[0],'label'=>$row[1]);
		}

		return $data;
	    }
	    else { die(mysql_query()); }
	}
    }

    function curLimit()
    {
	return $this->_limit_count;
    }

    function curPage()
    {
	return ceil($this->_limit_offset/$this->_limit_count)+1;
    }

    function _doQuery($query)
    {
	return mysql_query($query);
    }

    function _getDataArray()
    {
	if ( $this->_result = $this->_doQuery($this->_query) )
	{
	    while ( $row = mysql_fetch_assoc($this->_result) )
	    {
		$array[] = $row;
	    }

	    return $array;
	}
    }

    function countAll()
    {
	$this->_query = sprintf('SELECT COUNT(*) FROM `%s` %s', $this->_table, $this->_where($this->_filter,'AND',false));

	if ( $this->_result = mysql_query($this->_query) )
	{
	    $row = mysql_fetch_array($this->_result);
	    return $row[0];
	}
    }

    function _where($filter,$type,$encaps)
    {
	if ( empty($type) ) { $type = 'AND'; }

	if ( is_array($filter) )
	{
	    foreach ( $filter as $item )
	    {
		if ( sizeof($item) == 3 )
		{
		    if ( is_numeric($item[2]) )
		    {
			$array[] = sprintf('%s %s %d',$item[0],$item[1],$item[2]);
		    }
		    else
		    {
			$array[] = sprintf('%s %s \'%s\'',$item[0],$item[1],mysql_escape_string($item[2]));
		    }
		}
		elseif ( sizeof($item) == 2 )
		{
		    if ( is_numeric($item[1]) )
		    {
			$array[] = sprintf('%s=%d',$item[0],$item[1]);
		    }
		    elseif ( is_bool($item[1]) )
		    {
			$array[] = sprintf('%s IS %s NULL',$item[0],$item[1]?'NOT':false);
		    }
		    else
		    {
			$array[] = sprintf('%s=\'%s\'',$item[0],mysql_escape_string($item[1]));
		    }
		}
//		elseif ( sizeof($item) == 1 )
//		{
//		    $array[] = $item[0];
//		}
		elseif ( is_string($item) )
		{
		    $array[] = $item;
		}
	    }

	    if ( $encaps == false )
	    {
		return sprintf('WHERE %s',implode(" $type ",$array));
	    }
	    else
	    {
		return sprintf('(%s)',implode(" $type ",$array));
	    }
	}
    }

    function _order()
    {
	if ( !empty($this->_order_field) )
	{
	    return sprintf('ORDER BY `%s` %s',$this->_order_field,$this->_order_dir);
	}
    }

    function _limit()
    {
	return sprintf('LIMIT %d,%d',$this->_limit_offset,$this->_limit_count);
    }
}

class jqGrid extends DB
{
    function __construct($table)
    {
	if ( !empty($table) )
	{
	    parent::__construct();
	    $this->_table = $table;
	}
    }

    function spec($sw)
    {
	switch($this->_table)
	{
	    case	'zone_rate':
		return new jqRateZone;
	}
    }

    function countAll()
    {
	if ( empty($this->_count_query) )
	{
	    $this->_query = sprintf
	    (
		'SELECT `id` FROM `%s`',
		$this->_table
	    );
	}
	else
	{
	    $this->_query = $this->_count_query;
	}

	if ( mysql_query($this->_query) ) { return mysql_affected_rows(); }
    }

    function fields($fields)
    {
	if ( is_array($fields) )
	{
	    foreach ( $fields as $field )
	    {
		$this->_field[] = "`$field`";
	    }

	    return $this;
	}
    }

    function jqGridArray()
    {
	if ( empty($this->_query) )
	{
	    $this->_query = sprintf
	    (
		'SELECT %s FROM `%s` %s %s',
		implode(',',$this->_field),
		$this->_table,
		$this->_order(),
		$this->_limit()
	    );
	}

	if ( $this->_result = mysql_query($this->_query) )
	{
	    $data['records']	= $this->countAll();
	    $data['page']	= $this->curPage();
	    $data['total']	= ceil($data['records']/$this->_limit_count);

	    while($row=mysql_fetch_assoc($this->_result))
	    {
		$data['rows'][] = array('id'=>$row['id'],'cell'=>array_values($row));
	    }

	    return $data;
	}
    }
}
?>
